package com.v1.video.adapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.v1.video.R;
import com.v1.video.domain.PlayerInfo;
import com.v1.video.domain.SetHead;
import com.v1.video.util.Logger;

public class FriendsListAdapter extends BaseAdapter implements SectionIndexer {
	private Context mContext;

	public ArrayList<PlayerInfo> infos;
	public final String TAG = "FriendsListAdapter";
	private boolean isCanDouble = true;
	HashMap<String, Integer> alphaIndexer;
	public String[] sections;
	/**
	 * 如果只能单选，则本变量表示是否已有选择的；
	 */
	public boolean isSelected = false;
	/**
	 * 如果只能单选，则本变量表示已选择的pos；
	 */
	public int nSelectedPos = 0;

	String arr[] = { "#", "A", "B", "C", "d", "e", "f", "g", "h", "i", "j",
			"k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
			"x", "y", "z" };

	public FriendsListAdapter(Context context, ArrayList<PlayerInfo> infos,
			boolean isCanDouble) {
		mContext = context;
		this.infos = infos;
		this.isCanDouble = isCanDouble;
		alphaIndexer = new HashMap<String, Integer>();
		int size = infos.size();
		if (size > 0) {
			// int j = 0;
			for (int i = 0; i < size; i++) {
				// if(i % 4 == 0 && i != 0){
				// j++;
				// }
				// if(j >= arr.length){
				// j = 0;
				// }
				PlayerInfo info = infos.get(i);
				if (!alphaIndexer.containsKey(info.getDictName().toUpperCase())) {
					alphaIndexer.put(info.getDictName().toUpperCase(), i);
				}
				// info.setSortKey(arr[j].toUpperCase());
				// if(!alphaIndexer.containsKey(info.getSortKey())){
				// alphaIndexer.put(info.getSortKey(), i);
				// }

				// boolean isHas = false;
				// for(int k = 0; k < alphaIndexer.size();k++){
				// if(info.getSortKey().equals(alphaIndexer.))
				// }
				// if(!isHas){
				// alphaIndexer.put(info.getSortKey(), i);
				// }
			}

			Set<String> sectionLetters = alphaIndexer.keySet();

			// create a list from the set to sort
			ArrayList<String> sectionList = new ArrayList<String>(
					sectionLetters);

			Collections.sort(sectionList);

			sections = new String[sectionList.size()];

			sectionList.toArray(sections);
		}
		// Logger.i(TAG, "alphaIndexer.size="+alphaIndexer.size());
		// Logger.i(TAG, "sections.length="+sections.length);
		// for(int i = 0; i < sections.length;i++){
		// Logger.i(TAG, "sections["+i+"]"+sections[i]);
		// }
		// for(int i = 0; i < infos.size();i++){
		// Logger.i(TAG,
		// "infos.get("+i+").getSortKey()="+infos.get(i).getSortKey()+"--"+infos.get(i).getFocusUserName()
		// +"--"+getSectionForPosition(i));
		// }
	}

	@Override
	public int getCount() {
		return infos.size();
	}

	public void addList(List<PlayerInfo> list) {
		if (list != null) {
			if (this.infos != null) {
				for (int i = 0; i < list.size(); i++) {
					infos.add(list.get(i));
				}
			}
		}
		notifyDataSetChanged();
	}
	
	public void updataSelect(List<PlayerInfo> selectList){
		if(selectList != null){
			if(infos != null){
				for(int i = 0; i< selectList.size();i++){
					PlayerInfo user = selectList.get(i);
					for(int j = 0; j < infos.size();j++){
						PlayerInfo info = infos.get(j);
						if(info.getUserId() == user.getUserId()){
							info.setIsSelected(1);
							break;
						}
					}
				}
				notifyDataSetChanged();
			}
		}
	}

	@Override
	public Object getItem(int position) {
		return position;
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		ViewHolder holder = null;
		if (convertView != null && convertView instanceof LinearLayout)
			holder = (ViewHolder) convertView.getTag();
		else {
			holder = new ViewHolder();
			convertView = View.inflate(mContext, R.layout.item_friends_element,
					null);
			holder.userName = (TextView) convertView
					.findViewById(R.id.item_friends_name);
			holder.head = (ImageView) convertView
					.findViewById(R.id.item_friends_head);
			holder.isSelected = (ImageView) convertView
					.findViewById(R.id.item_friends_isselected);
			holder.sortKey = (TextView) convertView
					.findViewById(R.id.item_friends_sortkey);
			holder.sortKeyLayout = (RelativeLayout) convertView
					.findViewById(R.id.item_friends_sortback);
			convertView.setTag(holder);
		}

		final int pos = position;

		final PlayerInfo info = infos.get(position);
		int section = getSectionForPosition(position);
		if (position == getPositionForSection(section)) {
			holder.sortKey.setText(info.getDictName());
			holder.sortKeyLayout.setVisibility(View.VISIBLE);
		} else {
			holder.sortKeyLayout.setVisibility(View.GONE);
		}

		if(!TextUtils.isEmpty(info.getNickname())){
			holder.userName.setText(info.getNickname());
		} else if(!TextUtils.isEmpty(info.getUserName())){
			holder.userName.setText(info.getUserName());
		} else {
			holder.userName.setText("");
		}
		
		SetHead setHead = new SetHead();
		setHead.setHead(info.getUserImg(), info.getSex(), holder.head);
		convertView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Logger.i(TAG, "点击了...");
				if (isCanDouble) {
					if (!info.isExists()) {
						if (info.getIsSelected() == 0) {
							info.setIsSelected(1);
						} else {
							info.setIsSelected(0);
						}
					}

				} else {
					if (!info.isExists()) {
						if (isSelected) {
							if (pos != nSelectedPos) {
								info.setIsSelected(1);
								infos.get(nSelectedPos).setIsSelected(0);
								nSelectedPos = pos;
							}
						} else {
							isSelected = true;
							info.setIsSelected(1);
							nSelectedPos = pos;
						}
					}
				}
				notifyDataSetChanged();
			}
		});
		if (info.isExists()) {
			holder.isSelected.setImageResource(R.drawable.btn_selected_option);
		} else {
			if (info.getIsSelected() == 0) {
				holder.isSelected
						.setImageResource(R.drawable.btn_select_down_option);
			} else {
				holder.isSelected
						.setImageResource(R.drawable.btn_select_on_option);
			}
		}
		// holder.isSelected.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View arg0) {
		// // TODO Auto-generated method stub
		//
		// }
		// });

//		holder.head.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//
//				if (LoginInfo.getInstance().getUserId()
//						.equals(info.getUserId())) {
//					Intent center = new Intent();
//					center.setClass(mContext, PersonalCenterftActivity.class);
//					center.putExtra("userId", ""+info.getUserId());
//					mContext.startActivity(center);
//				} else {
//					Intent otherCenter = new Intent();
//					otherCenter.setClass(mContext, OtherPersonActivity.class);
//					otherCenter.putExtra("userId", ""+info.getUserId());
//					// otherCenter.putExtra("userId", info.getUserId());
//					mContext.startActivity(otherCenter);
//				}
//			}
//		});
		return convertView;
	}

	static class ViewHolder {
		RelativeLayout sortKeyLayout;

		TextView userName;// 用户名

		ImageView isSelected;

		ImageView head;

		TextView sortKey;

	}

	@Override
	public int getPositionForSection(int section) {
		// TODO Auto-generated method stub
		
		return alphaIndexer.get(sections[section]);
	}

	@Override
	public int getSectionForPosition(int pos) {
		// TODO Auto-generated method stub
		// String key = infos.get(pos).getSortKey();
		String key = infos.get(pos).getDictName();
		// int index = -1;
		// Logger.i(TAG, "key======"+key);
		for (int i = 0; i < sections.length; i++) {
			if (key.equals(sections[i])) {
				return i;
			}
		}
		return 1;
	}

	@Override
	public Object[] getSections() {
		// TODO Auto-generated method stub
		return sections;
	}

}
